package com.muqi.app.qlearn.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ToastUtil;
import com.muqi.app.qlearn.adapter.HomeBannerPageAdapter;
import com.muqi.app.qlearn.modles.Banner;
import com.muqi.app.qlearn.modles.GrowRewardAndMoveInfo;
import com.muqi.app.qlearn.modles.HomeBanner;
import com.muqi.app.qlearn.modles.Priase;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.BaseFragment;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.AcademicLevelActivity;
import com.muqi.app.qlearn.student.ui.ClassRoomCommentStatisticsActivity;
import com.muqi.app.qlearn.student.ui.ClassroomVedioActivity;
import com.muqi.app.qlearn.student.ui.GrowRecordActivity;
import com.muqi.app.qlearn.student.ui.HealthActivity;
import com.muqi.app.qlearn.student.ui.HomeDialogActivity;
import com.muqi.app.qlearn.student.ui.HwAndNotificationActivity;
import com.muqi.app.qlearn.student.ui.MainListActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.CircleLayout;
import com.muqi.app.user.widget.CircleLayout.OnItemClickListener;
import com.muqi.app.user.widget.CircleLayout.OnItemSelectedListener;
import com.muqi.app.user.widget.CircleMenuGroup.OnTouchItemScroll;
import com.muqi.app.user.widget.CircularImageView;
import com.muqi.app.user.widget.NoScrollViewPager;
import com.muqi.app.quser.transition.CustPagerTransformer;

public class TabHomeNew extends BaseChildFragment implements OnClickListener,
		OnTouchItemScroll, OnItemSelectedListener, OnItemClickListener,
		com.muqi.app.user.widget.CircleLayout.OnTouchItemScroll {
	private TextView homeTitle;
	private ChildReceiver receiver;
	private NoScrollViewPager mBanner;
	private CircleLayout mCircleLayout;
	private ImageView mIv_bg;
	private ImageView mIv;
	private List<HomeBanner> bannerDatas;
	private List<BaseFragment> fragments;
	private RotateAnimation mRotateUpAnim;
	private CircularImageView mCirUser;
	private String startTime;
	private String endTime;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBannerData();
		receiver = new ChildReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		filter.addAction(TabMine.BroadAction);
		getActivity().registerReceiver(receiver, filter);

	}

	@SuppressLint("InflateParams")
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View homeView = inflater.inflate(R.layout.fragment_home_new, null);
		initView(homeView);

		return homeView;
	}

	private void initView(View homeView) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy.M.d");
		Calendar calendar = Calendar.getInstance();

		if (calendar.get(Calendar.MONTH) + 1 <= 9) {
			startTime = (calendar.get(Calendar.YEAR) - 1) + ".9.1";
			endTime = format.format(calendar.getTime());
		} else {
			startTime = (calendar.get(Calendar.YEAR)) + ".9.1";
			endTime = format.format(calendar.getTime());
		}

		mBanner = (NoScrollViewPager) homeView
				.findViewById(R.id.home_viewpager);

		mCircleLayout = (CircleLayout) homeView
				.findViewById(R.id.home_circleLayout);
		mCircleLayout.setOnItemSelectedListener(this);
		mCircleLayout.setOnTouchItemScroll(this);
		mCircleLayout.setOnItemClickListener(this);
		mIv_bg = (ImageView) homeView.findViewById(R.id.iv_circle_bg1);
		mIv = (ImageView) homeView.findViewById(R.id.iv_circle_wai);

		homeTitle = (TextView) homeView.findViewById(R.id.home_title);
		if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
			if (currentChild != null) {
				homeTitle.setText(currentChild.name);
				homeTitle.setOnClickListener(this);
			}
		}

		mBanner.setAdapter(new HomeBannerPageAdapter(fragments,
				getChildFragmentManager()));
		mBanner.setPageTransformer(false, new CustPagerTransformer(mActivity));
		mBanner.setPageMargin(50);
		mBanner.setOffscreenPageLimit(8);
		mCirUser = (CircularImageView) homeView.findViewById(R.id.circle_user);
		homeView.findViewById(R.id.iv_home_directory).setOnClickListener(this);
		homeView.findViewById(R.id.iv_home_priase).setOnClickListener(this);
		GlideImageUtils.setAvatar(mActivity,mSpUtil.getCurrentAva(), mCirUser);
		

	}

	/**
	 * 初始化banner的数据
	 */
	private void initBannerData() {

		fragments = new ArrayList<BaseFragment>();
		
		
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.home.ordinal()));
		
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.vedio.ordinal()));
		//fragments.add(new BannerAcaFragment());
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.acad.ordinal()));
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.society.ordinal()));
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.art.ordinal()));
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.think.ordinal()));
		
		fragments.add(new BannerBodyFragment());
		
		fragments.add(new BannerFragment(R.layout.fragment_banner_home,Banner.comment.ordinal()));

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.home_title:
			showChildrenWindow(v);
			break;
		case R.id.iv_home_directory:
			startActivity(MainListActivity.class);
			break;
		case R.id.iv_home_priase:
			loadPriaseData();

			break;
		default:
			break;
		}
	}

	/**
	 * 加载各个模块中所占的比例
	 */
	private void loadPriaseData() {
		showLoading();
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("start_date", startTime);
		sendMap.put("end_date", endTime);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.COMPREHENSIVE_API, sendMap);

		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				hideLoading();
				if (resuleCode == RESULTCODE.SUCCESS) {
					ArrayList<GrowRewardAndMoveInfo> infos = ResponseUtils
							.getGrowStatisticsInfos(mActivity, result);
					if (infos != null && infos.size()>0) {
						Collections.sort(infos);
						Intent intent=null;
						Log.e("===",infos.get(0).data+"  "+infos.get(0).desc);
						if ("思想品德".equals(infos.get(0).desc)) {
							if ("male".equals(mSpUtil.getCurrentChildSex())) {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.boy_think.ordinal());
								startActivity(intent);
							} else {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.girl_think.ordinal());
								startActivity(intent);
							}
						} else if ("学业水平".equals(infos.get(0).desc)) {
							if ("male".equals(mSpUtil.getCurrentChildSex())) {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.boy_study.ordinal());
								startActivity(intent);
							} else {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.girl_study.ordinal());
								startActivity(intent);
							}
						} else if ("身心健康".equals(infos.get(0).desc)) {
							if ("male".equals(mSpUtil.getCurrentChildSex())) {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.boy_sport.ordinal());
								startActivity(intent);
							} else {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.girl_sport.ordinal());
								startActivity(intent);
							}
						} else if ("艺术培养".equals(infos.get(0).desc)) {
							if ("male".equals(mSpUtil.getCurrentChildSex())) {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.boy_art.ordinal());
								startActivity(intent);
							} else {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.girl_art.ordinal());
								startActivity(intent);
							}
						} else if ("社会实践".equals(infos.get(0).desc)) {
							if ("male".equals(mSpUtil.getCurrentChildSex())) {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.boy_help.ordinal());
								startActivity(intent);
							} else {
								intent = new Intent(mActivity,
										HomeDialogActivity.class);
								intent.putExtra("type", Priase.girl_help.ordinal());
								startActivity(intent);
							}
						}

					}else{
					       ToastUtil.showToast(mActivity, "无统计数据");
					}
				}

			}

		});

	}

	class ChildReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction()
					.equals(MContants.CHANGE_CURRENT_CHILD_ACTION)) {
				ChildBean child = (ChildBean) intent
						.getSerializableExtra(MContants.CHANGE_CURRENT_CHILD_DATAS);
				if (child != null) {
					homeTitle.setText(child.name);
					GlideImageUtils.setAvatar(mActivity, child.avatar_02, mCirUser);
				}
			}else if(intent.getAction().equals(TabMine.BroadAction)){
				GlideImageUtils.setAvatar(mActivity, mSpUtil.getCurrentAva(), mCirUser);
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		homeTitle.setText(myChild.name);
	}

	@Override
	public void onItemScroll(double fromAngle, final double endAngle) {
		mIv_bg.clearAnimation();
		mRotateUpAnim = new RotateAnimation((float) fromAngle,
				(float) endAngle, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		mRotateUpAnim.setFillAfter(true);
		mIv_bg.setAnimation(mRotateUpAnim);
		

	}

	@Override
	public void onItemClick(View view, int position, long id, String name) {
		Intent intent=new Intent(mActivity,GrowRecordActivity.class);
		switch ((int) id) {
		case R.id.art:
			intent.putExtra("type","F4");
			startActivity(intent);
			break;
		case R.id.think:
			intent.putExtra("type","F1");
			startActivity(intent);
			break;
		case R.id.health:
			startActivity(HealthActivity.class);
			break;
		case R.id.award:
			startActivity(ClassRoomCommentStatisticsActivity.class);
			break;
		case R.id.homework:
			startActivity(HwAndNotificationActivity.class);
			break;
		case R.id.video:
			startActivity(ClassroomVedioActivity.class);
			break;
		case R.id.academic:
			startActivity(AcademicLevelActivity.class);
			break;
		case R.id.social:
			intent.putExtra("type","F5");
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	@Override
	public void onItemSelected(View view, int position, long id, String name) {
		switch ((int) id) {
		case R.id.art:
			mBanner.setCurrentItem(4);
			break;
		case R.id.think:
			mBanner.setCurrentItem(5);
			break;
		case R.id.health:
			mBanner.setCurrentItem(6);
			break;
		case R.id.award:
			mBanner.setCurrentItem(7);
			break;
		case R.id.homework:
			mBanner.setCurrentItem(0);
			break;
		case R.id.video:
			mBanner.setCurrentItem(1);
			break;
		case R.id.academic:
			mBanner.setCurrentItem(2);
			break;
		case R.id.social:
			mBanner.setCurrentItem(3);
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemSelected(boolean select) {
		if (select) {
			mIv.setVisibility(View.VISIBLE);
		} else {
			mIv.setVisibility(View.GONE);
		}
	}

}
